package com.mall.service.mallLogs.listener;

import com.alibaba.fastjson.JSON;
import com.mall.model.domain.MallLogs;
import com.mall.service.mallLogs.mapper.MallLogsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 日志监听保存至数据库
 */
@Slf4j
@Component
public class MallLogsListener {

    @Autowired
    private MallLogsMapper mallLogsMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "mall.log.queue", durable = "true"),
            exchange = @Exchange(value = "mall.log.exchange", type = ExchangeTypes.TOPIC),
            key = "log.*"
    ))
    public void listenCreate(String message) throws ParseException {
        Map map = JSON.parseObject(message, Map.class);
        Long userId = Long.valueOf(map.get("userId").toString());
        String currentTimeStr = (String) map.get("currentTime");
        Date currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(currentTimeStr);
        String methodUrl = (String) map.get("methodUrl");
        String method = (String) map.get("method");
        Long time = Long.valueOf(map.get("time").toString());
        Integer isTimeout = Integer.valueOf(map.get("isTimeout").toString());

        log.info("接收到订阅消息：{}", message);
        //存入数据库
        MallLogs mallLogs = new MallLogs();
        mallLogs.setUserId(userId);
        mallLogs.setCurrentTime(currentTime);
        mallLogs.setMethodUrl(methodUrl);
        mallLogs.setMethod(method);
        mallLogs.setTime(time);
        mallLogs.setIsTimeout(isTimeout);
        mallLogsMapper.save(mallLogs);
    }
}
